import 'dart:async';

import 'package:chatbot/manager/dio_manager.dart';
import 'package:chatbot/manager/event_bus.dart';
import 'package:chatbot/manager/product_manager.dart';
import 'package:chatbot/manager/store_manager.dart';
import 'package:chatbot/model/event.dart';
import 'package:chatbot/page/fuwu.dart';
import 'package:chatbot/page/privacy_page.dart';
import 'package:chatbot/utils/colors.dart';
import 'package:chatbot/utils/utils.dart';
import 'package:chatbot/widget/progress/progress_dialog.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

class VipPage extends StatefulWidget {
  String fromPage;
  VipPage(this.fromPage);
  @override
  State<StatefulWidget> createState() {
    return VipState();
  }
}

class VipState extends State<VipPage> {
  late StreamSubscription eventSubscription;

  @override
  void initState() {
    super.initState();
    eventSubscription = EventManager.instance.eventBus
        .on<PurchaseUpdateEvent>()
        .listen((event) {
      debugPrint("PurchaseSuccessEvent");
      addCoins();
      if (mounted) {
        Future.delayed(const Duration(milliseconds: 500), () {
          Navigator.pop(context);
        });
      }
    });
    if (ProductManager.instance.products.isEmpty) {
      loadProductList();
    }
  }

  addCoins() async{
    debugPrint("addCoins coins=${StoreManager.getPurchasePrice()} fromPage=${widget.fromPage}");
    Response response = await DioManager.instance.dio.post(
      "token/coins/updateV2",
      data: {
        "coins":StoreManager.getPurchasePrice(),
        "fromPage":widget.fromPage
      },
    );
    debugPrint("response=${response.toString()}");
  }
  loadProductList() async {
    await ProductManager.instance.getProductList();
    Future.delayed(const Duration(milliseconds: 500), () {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ChatColors.lightColor,
      body: Stack(
        children: [
          Image.asset(
            'assets/images/vip_bg.jpg',
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            fit: BoxFit.cover,
          ),
          ProductManager.instance.products.isEmpty
              ? Center(
                  child: CupertinoActivityIndicator(
                      radius: 10.0, color: ChatColors.primaryColor),
                )
              : SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Padding(
                        padding: EdgeInsets.only(
                            left: 10.0,
                            right: 16,
                            top: MediaQuery.of(context).padding.top + 32),
                        child: Image.asset(
                          'assets/images/vip.png',
                          width: MediaQuery.of(context).size.width - 32,
                          fit: BoxFit.fitWidth,
                        ),
                      ),
                      Container(
                        height: 90,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            width: 12,
                          ),
                          getItem("周会员", ProductManager.instance.getWeekProductDetail().price, const Color(0xFFfe375f), () {
                            purchase(ProductManager.instance.getWeekProductDetail());
                          }),
                          getItem("年会员", ProductManager.instance.getYearProductDetail().price, const Color(0xFF0a84fe), () {
                            purchase(ProductManager.instance.getYearProductDetail());
                          },
                              withTag: true),
                          getItem("月会员", ProductManager.instance.getMonthProductDetail().price, const Color(0xFFfe375f), () {
                            purchase(ProductManager.instance.getMonthProductDetail());
                          }),
                          Container(
                            width: 12,
                          ),
                        ],
                      ),
                      Container(
                        height: 12,
                      ),
                      Container(
                          margin: const EdgeInsets.fromLTRB(24, 0, 24, 4),
                          child: RichText(
                              text: const TextSpan(children: <TextSpan>[
                            TextSpan(
                              text:
                                  "您可通过前往iTunes账号设置并取消订阅的方式,必须在当前有效期结束前至少24小时禁用，否则将自动续费.我们将在当前有效期结束前24小时内向您的账号收取续订费用,订阅款项将从您的iTunes账户中扣除. 请注意：试用期（如果提供）的任何未使用部分将在用户购买该出版物的订阅时（如果适用）失效。了解更多信息,请参阅我们的",
                              style:
                                  TextStyle(color: Colors.grey, fontSize: 11),
                            ),
                          ]))),
                      Container(
                          margin: const EdgeInsets.fromLTRB(24, 0, 24, 4),
                          child: RichText(
                              text: TextSpan(children: <TextSpan>[
                            const TextSpan(
                              text: "注:点击购买/续费视为您已阅读并同意",
                              style:
                                  TextStyle(color: Colors.grey, fontSize: 11),
                            ),
                            TextSpan(
                              text: "用户协议、",
                              style: const TextStyle(
                                  decoration: TextDecoration.underline,
                                  decorationStyle: TextDecorationStyle.solid,
                                  color: Colors.grey,
                                  fontSize: 11),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  Navigator.push(context, CupertinoPageRoute(
                                      builder: (BuildContext context) {
                                    return FuwuPage();
                                  }));
                                },
                            ),
                            TextSpan(
                              text: "隐私条款",
                              style: const TextStyle(
                                  decoration: TextDecoration.underline,
                                  decorationStyle: TextDecorationStyle.solid,
                                  color: Colors.grey,
                                  fontSize: 11),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  Navigator.push(context, CupertinoPageRoute(
                                      builder: (BuildContext context) {
                                    return PrivacyPage();
                                  }));
                                },
                            ),
                          ]))),
                      Container(
                        height: 12 + MediaQuery.of(context).padding.bottom,
                      )
                    ],
                  ),
                ),
          Positioned(
            top: MediaQuery.of(context).padding.top,
            left: 12,
            child: IconButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                icon: Icon(
                  Icons.close,
                  color: Colors.grey.withOpacity(0.6),
                  size: 20,
                )),
          ),
          Positioned(
              top: MediaQuery.of(context).padding.top + 12,
              right: 12,
              child: InkWell(
                onTap: (){
                  restore();
                },
                child: Text(
                  "恢复",
                  style: TextStyle(
                      color: Colors.grey.withOpacity(0.6), fontSize: 13),
                ),
              ))
        ],
      ),
    );
  }

  restore() async{
    var pd = ProgressDialog(context: context);
    pd.show(
      barrierDismissible: false,
      msg: "请稍等...",
      hideValue: true,
    );
    await InAppPurchase.instance.restorePurchases();
    pd.close();
    if(StoreManager.isVip()){
      Utils.showToast("恢复成功");
    }else{
      Utils.showToast("恢复失败");
    }
  }
  purchase(ProductDetails productDetails) {
    final PurchaseParam purchaseParam =
        PurchaseParam(productDetails: productDetails);
    InAppPurchase.instance.buyConsumable(purchaseParam: purchaseParam);
  }

  getItem(String title, String price, Color color, VoidCallback callback,
      {bool withTag = false}) {
    return InkWell(
      onTap: callback,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            width: (MediaQuery.of(context).size.width - 80) / 3,
            margin: const EdgeInsets.only(top: 20),
            height: 142,
            decoration: BoxDecoration(
              color: color,
              borderRadius: const BorderRadius.all(Radius.circular(16.0)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  height: 24,
                ),
                Text(
                  title,
                  style: const TextStyle(
                      color: Colors.white,
                      fontSize: 14.5,
                      fontWeight: FontWeight.w600),
                ),
                Container(
                  height: 12,
                ),
                Text(
                  price,
                  style: const TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.w800),
                ),
                Container(
                  height: 24,
                ),
                Text(
                  "自动续费",
                  style: TextStyle(
                      color: Colors.white.withOpacity(0.5),
                      fontSize: 11,
                      fontWeight: FontWeight.w200),
                ),
                Container(
                  height: 12,
                ),
              ],
            ),
          ),
          withTag
              ? Positioned(
                  top: 1,
                  child: Image.asset(
                    'assets/images/dazhe.png',
                    width: 84,
                    height: 42,
                    fit: BoxFit.contain,
                  ))
              : Container()
        ],
      ),
    );
  }
}
